package info.thereisonlywe.onenesspathfinder.ui;

import info.thereisonlywe.core.project.ProjectConstants;
import info.thereisonlywe.core.project.ProjectLocalization;
import info.thereisonlywe.core.toolkit.FontToolkit;
import info.thereisonlywe.core.toolkit.GUIToolkit;
import info.thereisonlywe.core.ui.swing.extensions.table.EmptyCellEditor;
import info.thereisonlywe.core.ui.swing.extensions.table.TextAreaRenderer;
import info.thereisonlywe.quran.QuranicVerse;
import info.thereisonlywe.quran.bookmark.QuranicBookmarkList;
import info.thereisonlywe.quran.text.QuranicTextList;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.BorderFactory;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.ToolTipManager;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumnModel;

public class SimilarVersesDialog {

	private static JDialog dialog;
	private static JScrollPane scrollPane;
	private static JTable table;
	private static QuranicVerse[] similarVerses;
	private static final JPopupMenu popupMenu_Dialog = new JPopupMenu();

	/**
	 * @wbp.parser.entryPoint
	 */
	private static void init()
	{
		if (dialog != null) return;
		dialog = new JDialog();
		dialog.setResizable(false);
		dialog.setIconImage(null);
		dialog.setTitle(ProjectLocalization.getString(
				ProjectConstants.ONENESS_PATHFINDER_PROJECT,
				"BrowseSimilarVerses"));
		dialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		dialog.setPreferredSize(new Dimension(500, 350));
		dialog.setSize(new Dimension(500, 350));
		dialog.setModal(true);
		dialog.getContentPane().setLayout(new BorderLayout());

		scrollPane = new JScrollPane();
		table = new JTable();
		table.setTableHeader(null);
		table.setForeground(Color.black);
		table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		table.setSelectionBackground(Color.LIGHT_GRAY);
		table.setSelectionForeground(Color.black);
		SimilarVersesTableModel model = new SimilarVersesTableModel();
		// model.addTableModelListener(new TableListener());
		table.setModel(model);
		table.getColumnModel().getColumn(0)
				.setCellRenderer(new SimilarVersesTableRenderer());
		table.getColumnModel().getColumn(0)
				.setCellEditor(new EmptyCellEditor());
		ToolTipManager.sharedInstance().unregisterComponent(table);
		scrollPane.setBackground(Color.white);
		scrollPane.setViewportView(table);
		dialog.getContentPane().add(scrollPane, BorderLayout.CENTER);
		initListeners();
		initPopupMenu();
	}

	private static void initListeners()
	{

		KeyboardFocusManager.getCurrentKeyboardFocusManager()
				.addKeyEventDispatcher(new KeyEventDispatcher()
				{
					@Override
					public boolean dispatchKeyEvent(KeyEvent e)
					{
						boolean keyHandled = false;
						if (e.getID() == KeyEvent.KEY_PRESSED)
						{
							if (e.getKeyCode() == KeyEvent.VK_ESCAPE
									&& dialog.isVisible())
							{
								dialog.setVisible(false);
								UIDelegate.setOpenDialog(false);
								keyHandled = true;
							}
						}
						return keyHandled;
					}
				});

		dialog.addWindowListener(new WindowAdapter()
		{
			@Override
			public void windowClosing(WindowEvent e)
			{
				dialog.setVisible(false);
				UIDelegate.setOpenDialog(false);
			}
		});

		table.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{
				if (e.getClickCount() == 2)
				{
					int indices[] = table.getSelectedRows();
					if (indices.length == 1)
					{
						dialog.setVisible(false);
						UIDelegate.setOpenDialog(false);
						UIDelegate.seekToVerse(similarVerses[indices[0]]);
					}
				}
			}

			@Override
			public void mousePressed(MouseEvent e)
			{
				if (e.isPopupTrigger())
				{
					refreshPopupMenu();
					popupMenu_Dialog.show(e.getComponent(), e.getX(), e.getY());
				}
			}

			@Override
			public void mouseReleased(MouseEvent e)
			{
				if (e.isPopupTrigger())
				{
					refreshPopupMenu();
					popupMenu_Dialog.show(e.getComponent(), e.getX(), e.getY());
				}
			}
		});

	}

	public static QuranicVerse[] getSelectedVerses()
	{
		int rows[] = table.getSelectedRows();
		QuranicVerse[] results = new QuranicVerse[rows.length];
		for (int i = 0; i < results.length; i++)
		{
			results[i] = similarVerses[rows[i]];
		}
		return results;
	}

	private static void refreshPopupMenu()
	{
		if (table.getSelectedRows().length > 0)
		{
			popupMenu_Dialog.getComponent(0).setEnabled(true);
			popupMenu_Dialog.getComponent(1).setEnabled(true);
		}
		else
		{
			popupMenu_Dialog.getComponent(0).setEnabled(false);
			popupMenu_Dialog.getComponent(1).setEnabled(false);
		}

	}

	private static void initPopupMenu()
	{
		JMenuItem item = new JMenuItem(ProjectLocalization.getString(
				ProjectConstants.ONENESS_PATHFINDER_PROJECT, "AddToBookmarks"));
		item.setMargin(UIConstants.MARGIN);
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				UIDelegate.BookmarkPaneHook.getBookmarkList()
						.addBookmarks(
								getSelectedVerses(),
								"~"
										+ UIDelegate.getDisplayedVerse()
												.toNotationString());
				UIDelegate.BookmarkPaneHook.refresh();

			}
		});
		popupMenu_Dialog.add(item);

		item = new JMenuItem(ProjectLocalization.getString(
				ProjectConstants.CORE_PROJECT, "Save"));
		item.setMargin(UIConstants.MARGIN);
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				QuranicBookmarkList qbl = new QuranicBookmarkList();
				qbl.addBookmarks(getSelectedVerses(), "~ "
						+ UIDelegate.getDisplayedVerse().toNotationString());
				SaveBookmarksDialog.showDialog(qbl.getBookmarks());
				qbl = null;

			}
		});
		popupMenu_Dialog.add(item);

		popupMenu_Dialog.addSeparator();
		item = new JMenuItem(ProjectLocalization.getString(
				ProjectConstants.CORE_PROJECT, "SelectAll"));
		item.setMargin(UIConstants.MARGIN);
		item.setAccelerator(KeyStroke.getKeyStroke("ctrl A"));
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				table.getSelectionModel().setSelectionInterval(0,
						similarVerses.length - 1);
			}
		});
		popupMenu_Dialog.add(item);
	}

	public static void showDialog()
	{
		init();
		similarVerses = UIDelegate.getDisplayedVerse().getSimilarVerses();
		dialog.setLocation(GUIToolkit.getCenteredWindowPosition(
				dialog.getWidth(), dialog.getHeight()));
		scrollPane
				.setComponentOrientation(QuranicTextList.getPreferred() < 0 ? ComponentOrientation.RIGHT_TO_LEFT
						: ComponentOrientation.LEFT_TO_RIGHT);
		((AbstractTableModel) table.getModel()).fireTableDataChanged();
		UIDelegate.setOpenDialog(true);
		dialog.setVisible(true);
	}

	private static class SimilarVersesTableModel extends AbstractTableModel {

		private static final long serialVersionUID = -4179998068419126729L;

		public SimilarVersesTableModel()
		{
		}

		@Override
		public int getRowCount()
		{
			return similarVerses.length;
		}

		@Override
		public int getColumnCount()
		{
			return 1;
		}

		@Override
		public Object getValueAt(int rowIndex, int columnIndex)
		{
			int preferred = QuranicTextList.getPreferred();

			if (preferred < 0) return similarVerses[rowIndex].getContent();

			else
			{
				return QuranicTextList.getText(preferred).getVerseContent(
						similarVerses[rowIndex]);
			}
		}

		@Override
		public Class<?> getColumnClass(int columnIndex)
		{
			return String.class;
		}

	}

	private static class SimilarVersesTableRenderer extends TextAreaRenderer {

		private static final long serialVersionUID = -7875836626302331669L;

		private static final TitledBorder border = BorderFactory
				.createTitledBorder(
						BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
						"0", 0, TitledBorder.TOP,
						FontToolkit.changeFontSize(table.getFont(), -2),
						new Color(73, 43, 98));

		public SimilarVersesTableRenderer()
		{
			super();
		}

		@Override
		public Component getTableCellRendererComponent(JTable table,
				Object obj, boolean isSelected, boolean hasFocus, int row,
				int column)
		{
			adaptee.getTableCellRendererComponent(table, obj, isSelected,
					hasFocus, row, column);
			int pref = QuranicTextList.getPreferred();
			if (pref == -1 || QuranicTextList.getText(pref).isRTL()) setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
			else setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
			setForeground(adaptee.getForeground());
			setBackground(adaptee.getBackground());
			border.setTitle(similarVerses[row].toNotationString());
			border.setTitleJustification(pref == -1
					|| QuranicTextList.getText(pref).isRTL() ? Integer
					.valueOf(TitledBorder.RIGHT) : Integer
					.valueOf(TitledBorder.LEFT));
			setBorder(border);
			// if (pref == -1) setFont(FontLibrary.get(FontLibrary.SCHERAZADE,
			// 24));
			// else setFont(FontLibrary.get(FontLibrary.CODE2000, 14));
			setText(adaptee.getText());
			TableColumnModel columnModel = table.getColumnModel();
			setSize(columnModel.getColumn(column).getWidth(), 100000);
			int height_wanted = (int) getPreferredSize().getHeight();
			addSize(table, row, column, height_wanted);
			height_wanted = findTotalMaximumRowSize(table, row);
			if (height_wanted != table.getRowHeight(row))
			{
				table.setRowHeight(row, height_wanted);
			}
			return this;
		}

		@Override
		public void invalidate()
		{
		}

		@Override
		public void repaint()
		{
		}
	}

}
